package com.avalon.shop.controller;

import com.avalon.core.model.RecordRow;
import com.avalon.shop.service.FavoriteService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/favorite")
public class FavoriteController {
    private FavoriteService favoriteService;

    public FavoriteController(FavoriteService favoriteService) {
        this.favoriteService = favoriteService;
    }

    @PostMapping("/add")
    public void addFavorite(@RequestBody Map<String, Object> param) {
        favoriteService.addModel(param);
    }

    @PostMapping("/get/all")
    public List<Map> getAllFavorite(@RequestBody Map<String, Object> param) {
        Integer userId = 0;
        if (param.containsKey("userId")) {
            userId = Integer.parseInt(param.get("userId").toString());
        }
        return favoriteService.getAllFavorite(userId);
    }

    @PostMapping("/get/one")
    public RecordRow getOneFavorite(@RequestBody Map<String, Object> param) {
        Integer userId = 0;
        if (param.containsKey("userId")) {
            userId = Integer.parseInt(param.get("userId").toString());
        }
        Integer commodityId = 0;
        if (param.containsKey("commodityId")) {
            commodityId = Integer.parseInt(param.get("commodityId").toString());
        }
        List<Map> oneFavorite = favoriteService.getOneFavorite(userId, commodityId);
        if (!oneFavorite.isEmpty()) {
            return RecordRow.build().put("id", oneFavorite.get(0).get("id"));
        }
        return RecordRow.build();
    }

    @PostMapping("/delete")
    public void deleteFavorite(@RequestBody Map<String, Object> param) {
        Integer id = 0;
        if (param.containsKey("id")) {
            id = Integer.parseInt(param.get("id").toString());
        }
        favoriteService.deleteModel(id);
    }
}
